package com.zhkj.txg.module.home.adapter

import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zhkj.txg.R
import com.zhkj.txg.module.home.entity.CateSortUIEntity

class CateSortAdapter :
    BaseQuickAdapter<CateSortUIEntity, BaseViewHolder>(R.layout.item_cate_sort) {

    private var selectedPosition = 0
    var sortCallback: SortCallback? = null

    init {
        setOnItemClickListener { _, _, position ->
            if (selectedPosition == position && data[position].canSort) {
                data[position].sortAsc = !data[position].sortAsc
            } else if (selectedPosition == position && !data[position].canSort) return@setOnItemClickListener
            selectedPosition = position
            notifyDataSetChanged()
            sortCallback?.sort(data[position])
        }
    }

    override fun convert(helper: BaseViewHolder, item: CateSortUIEntity) {
        val imageView = helper.setText(R.id.tvSortName, item.name)
            .setGone(R.id.ivSortOrder, !item.canSort).getView<ImageView>(R.id.ivSortOrder)
        // 判断是否选中
        helper.itemView.isSelected = selectedPosition == helper.layoutPosition
        // 判断是否有排序
        if (item.canSort) when {
            selectedPosition != helper.layoutPosition -> {// 默认状态
                imageView.setImageResource(R.drawable.ic_cate_sort_default)
            }
            item.sortAsc -> { // 升序
                imageView.setImageResource(R.drawable.ic_sort_down)
            }
            else -> { // 降序
                imageView.setImageResource(R.drawable.ic_sort_up)
            }
        }
    }

    fun getSelectSort(): CateSortUIEntity {
        return data[selectedPosition]
    }
}

interface SortCallback {
    fun sort(sort: CateSortUIEntity)
}